<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex" style="position: relative">
    <DataSourceTree class="w-1/4 xl:w-1/5" @select="handleSelect" />
    <BasicTable @register="registerTable" class="w-3/4 xl:w-4/5" :searchInfo="searchInfo">
      <template #toolbar>
        <a-button type="primary" @click="handleGlobalConfig"> 全局配置</a-button>
        <a-button type="primary" @click="handleBatchGen"> 批量生成</a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: '预览',
              onClick: handlePreview.bind(null, record),
            },
            {
              label: '生成',
              color: 'error',
              popConfirm: {
                title: '是否确认生成',
                confirm: handleGen.bind(null, record),
              },
            },
            {
              label: '配置',
              color: 'error',
              onClick: handleConfig.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <CodeGenPreviewDrawer @register="registerPreviewDrawer" @success="handleCodePreViewSuccess" />
    <CodeGeConfigDrawer
      @register="registerGenConfigDrawer"
      @success="handleGenConfigSuccess"
      @save="handleSaveGenConfig"
      width="100%"
      :get-container="false"
      :style="{ position: 'absolute' }"
    />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { reactive, ref } from 'vue';
  import { defaultCodeGenConfig, getKeyIdentityInfo, transferTableData, useCodeGen } from '.';
  import DataSourceTree from './DataSourceTree.vue';
  import { PageWrapper } from '/@/components/Page';
  import { columns, searchFormSchema } from './gencode.data';
  import { CodeGenConfigParams, GenDataSourceConfig } from '/@/api/gen/model/CodeGenModel';
  import { getTableInfoList } from '/@/api/gen/table';
  import { DataSourceParams } from '/@/api/gen/model/DataSourceModel';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useTable, BasicTable, TableAction } from '/@/components/Table';
  import CodeGenPreviewDrawer from './CodeGenPreviewDrawer.vue';
  import CodeGeConfigDrawer from './CodeGeConfigDrawer.vue';
  import { useDrawer } from '/@/components/Drawer';
  import { getGenConfig } from '/@/utils/gen/config-cache';

  // 代码生成配置
  const genConfig = ref<CodeGenConfigParams>();
  const searchInfo = ref();
  //当前数据源
  const currentDataSource = ref<GenDataSourceConfig>();
  // 消息提示
  const { createMessage } = useMessage();
  // 初始化表格数据
  const [registerTable, { reload }] = useTable({
    title: '数据表',
    api: getTableInfoList, //列表接口
    columns, // 表格的每一列
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema, // 查询条件表单
    },
    clickToRowSelect: false,
    useSearchForm: true,
    showTableSetting: true,
    showIndexColumn: false,
    immediate: false,
    bordered: true,
    actionColumn: {
      fixed: 'right',
      width: 150,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    rowSelection: {
      type: 'checkbox',
    },
  });

  //抽屉
  const [registerPreviewDrawer, { openDrawer: openPreviewDrawer }] = useDrawer();
  const [registerGenConfigDrawer, { openDrawer: opeConfigDrawer }] = useDrawer();

  //生成配置处理
  function handleConfig(row) {
    //添加配置
    setCodeGenConfig(row);
    opeConfigDrawer(true, {
      row,
      genConfig: genConfig.value,
      codeGenApi: genCodeInner,
      downloadZip: downloadZip,
    });
  }

  //代码生成
  function handleGen(row) {
    //添加配置
    setCodeGenConfig(row);
    const gen = genConfig.value!.genBaseConfigEntity.genMode === 'zip' ? downloadZip : genCodeInner;
    gen().then((res) => {
      if (res) {
        createMessage.success('代码生成成功');
      }
    });
  }

  //预览处理
  function handlePreview(row) {
    //添加配置
    setCodeGenConfig(row);
    openPreviewDrawer(true, {
      title: row.name,
      previewApi: previewCode,
    });
  }

  //设置生成配置
  function setCodeGenConfig(row) {
    genConfig.value = defaultCodeGenConfig as unknown as CodeGenConfigParams;
    genConfig.value.genDataSourceEntity = currentDataSource.value!;
    //默认配置
    genConfig.value.genTableConfigs[0].businessName = row.comment;
    genConfig.value.genTableConfigs[0].tableName = row.name;
    genConfig.value.genTableConfigs[0].tableComment = row.comment;

    const fieldConfigs = transferTableData(
      reactive([
        ...row.fields,
        ...row.commonFields.map((i) => {
          i.isCommon = true;
          return i;
        }),
      ]),
    );
    const keyIdentityInfo = getKeyIdentityInfo(fieldConfigs);
    genConfig.value.genTableConfigs[0].tableFieldConfig = fieldConfigs;
    genConfig.value.genTableConfigs[0].keyFlag = keyIdentityInfo.keyFlag;
    genConfig.value.genTableConfigs[0].keyName = keyIdentityInfo.keyName;
    const key = `${genConfig.value.genDataSourceEntity.dbinfoId}::${genConfig.value?.genDataSourceEntity.dbName}::${row.name}`;
    //如果缓存有就取缓存的
    if (getGenConfig(key)) {
      genConfig.value = getGenConfig(key);
    }
  }

  //批量生成处理
  function handleBatchGen() {
    //TODO
    createMessage.warn('功能开发中...');
  }

  //全局配置处理
  function handleGlobalConfig() {
    //TODO
    createMessage.warn('功能开发中...');
  }

  //预览完成回调
  function handleCodePreViewSuccess() {}

  //配置完成回调
  function handleGenConfigSuccess() {}

  //保存配置回调
  function handleSaveGenConfig() {}

  // 代码生成
  const { downloadZip, genCodeInner, previewCode } = useCodeGen({
    genConfig,
  });

  //tree节点点击
  async function handleSelect(val: DataSourceParams) {
    //设置数据源
    currentDataSource.value = val as GenDataSourceConfig;
    searchInfo.value = val;
    reload({ searchInfo: val });
  }
</script>

<style lang="less" scoped></style>
